home *** CD-ROM | disk | FTP | other *** search
/ Scene 96 / Scene 96 International Edition (Zyklop Software) (Disc 2) (1997).iso / misc / coding / midas060 / src / loadxm.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-25  |  49.0 KB  |  1,507 lines

  1. /*      loadxm.c
  2.  *
  3.  * Generic Module Player Fasttracker 2 Module loader
  4.  *
  5.  * $Id: loadxm.c,v 1.12 1997/01/25 15:23:16 pekangas Exp $
  6.  *
  7.  * Copyright 1996,1997 Housemarque Inc.
  8.  *
  9.  * This file is part of the MIDAS Sound System, and may only be
  10.  * used, modified and distributed under the terms of the MIDAS
  11.  * Sound System license, LICENSE.TXT. By continuing to use,
  12.  * modify or distribute this file you indicate that you have
  13.  * read the license and understand and accept it fully.
  14. */
  15.  
  16. /* Note! Loading an XM module requires INSANE amounts of memory for buffers
  17.    - 90kb for pattern buffers (for 32 channels) plus the size of the largest
  18.    sample for samples. */
  19.  
  20. #include "lang.h"
  21. #include "mtypes.h"
  22. #include "errors.h"
  23. #include "mglobals.h"
  24. #include "mmem.h"
  25. #include "file.h"
  26. #include "sdevice.h"
  27. #include "gmplayer.h"
  28. #include "xm.h"
  29. #ifndef NOEMS
  30. #include "ems.h"
  31. #endif
  32. #include "mutils.h"
  33.  
  34. #ifdef __WC32__
  35. #include <malloc.h>
  36. #endif
  37.  
  38. #include <stdio.h>
  39.  
  40. RCSID(const char *loadxm_rcsid = "$Id: loadxm.c,v 1.12 1997/01/25 15:23:16 pekangas Exp $";)
  41.  
  42. /*#define CHECK_THE_HEAP*/
  43.  
  44. extern ulong *__nheapbeg;
  45.  
  46. /*#define DEBUGMESSAGES*/
  47.  
  48.  
  49. /****************************************************************************\
  50. *
  51. * Function:     TestHeap(void)
  52. *
  53. * Description:  Test if the heap is corrupted. Watcom C ONLY! Implemented here
  54. *               because the Watcom _heapchk() often reports the heap is OK
  55. *               even though it isn't.
  56. *
  57. * Returns:      MIDAS error code
  58. *
  59. \****************************************************************************/
  60.  
  61. #if defined(CHECK_THE_HEAP) && defined(__WC32__)
  62.     /* Maximum valid block in heap: */
  63. #define MAXBLK (2048*1024)
  64.  
  65. static int TestHeap(void)
  66. {
  67.     static struct _heapinfo hinfo;
  68.     int         hstatus;
  69.     unsigned    len;
  70.  
  71.     hinfo._pentry = NULL;
  72.  
  73.     while ( 1 )
  74.     {
  75.         hstatus = _heapwalk(&hinfo);
  76.         if ( hstatus != _HEAPOK )
  77.             break;
  78.         len = hinfo._size;
  79.         if ( (len == 0) || (len > MAXBLK) || (len & 3) )
  80.             return errHeapCorrupted;
  81.     }
  82.  
  83.     if ( (hstatus == _HEAPEND) || (hstatus == _HEAPEMPTY) )
  84.         return OK;
  85.     return errHeapCorrupted;
  86. }
  87. #define CHECKHEAP \
  88.     { \
  89.         if ( TestHeap() != OK ) \
  90.         { \
  91.             puts("HEAP CORRUPTED!"); \
  92.             ERROR(errHeapCorrupted, ID_gmpLoadXM); \
  93.             LoadError(); \
  94.             return errHeapCorrupted; \
  95.         } \
  96.     }
  97.  
  98. #else
  99. #define CHECKHEAP
  100. #endif
  101.  
  102. /* Pass error code in variable "error" on, used in gmpLoadXM(). */
  103. #define PASSERR() { LoadError(); PASSERROR(ID_gmpLoadXM) }
  104.  
  105.  
  106. /* Conversion table from FT2 command number to GMP ones: */
  107. static uchar ft2Commands[36] =
  108. {
  109.     gmpcArpeggio,               /* 0 - Arpeggio */
  110.     gmpcSlideUp,                /* 1 - Portamento up */
  111.     gmpcSlideDown,              /* 2 - Portamento down */
  112.     gmpcTonePortamento,         /* 3 - Tone portamento */
  113.     gmpcVibrato,                /* 4 - Vibrato */
  114.     gmpcTPortVSlide,            /* 5 - Tone portamento + volume slide */
  115.     gmpcVibVSlide,              /* 6 - Vibrato + volume slide */
  116.     gmpcTremolo,                /* 7 - Tremolo */
  117.     gmpcSetPanning,             /* 8 - Set panning (extension) */
  118.     gmpcSampleOffset,           /* 9 - Sample offset */
  119.     gmpcVolumeSlide,            /* A - Volume slide */
  120.     gmpcPositionJump,           /* B - Position jump */
  121.     gmpcSetVolume,              /* C - Set volume */
  122.     gmpcPatternBreak,           /* D - Pattern break */
  123.     gmpcNone,                   /* E - E-commands (see below) */
  124.     gmpcSetSpeed,               /* F - Set speed/tempo */
  125.     gmpcSetMVolume,             /* G - Set master volume */
  126.     gmpcMVolSlide,              /* H - Master volume slide */
  127.     gmpcNone,                   /* I - Unused */
  128.     gmpcNone,                   /* J - Unused */
  129.     gmpcNone,                   /* K - Unused */
  130.     gmpcNone,                   /* L - Set envelope position */
  131.     gmpcNone,                   /* M - Unused */
  132.     gmpcNone,                   /* N - Unused */
  133.     gmpcNone,                   /* O - Unused */
  134.     gmpcPanSlide,               /* P - Panning slide */
  135.     gmpcNone,                   /* Q - Unused */
  136.     gmpcS3MRetrig,              /* R - ST3 multi retrig */
  137.     gmpcNone,                   /* S - Unused */
  138.     gmpcNone,                   /* T - Tremor */
  139.     gmpcNone,                   /* U - Unused */
  140.     gmpcNone,                   /* V - Unused */
  141.     gmpcMusicSync,              /* W - Music Synchronization (extension) */
  142.     gmpcNone,                   /* Extra fine slides - handled separately */
  143.     gmpcNone,                   /* Y - Unused */
  144.     gmpcNone,                   /* Z - Unused */
  145. };
  146.  
  147. /* Conversion table from FT2 E-command numbers to GMP commands: */
  148. static uchar ft2ECommands[16] =
  149. {
  150.     gmpcNone,                   /* E0 - Toggle filter */
  151.     gmpcFineSlideUp,            /* E1 - Fine portamento up */
  152.     gmpcFineSlideDown,          /* E2 - Fine portamento down */
  153.     gmpcNone,                   /* E3 - Set glissando control */
  154.     gmpcNone,                   /* E4 - Set vibrato type */
  155.     gmpcNone,                   /* E5 - Set finetune */
  156.     gmpcPatternLoop,            /* E6 - Pattern loop */
  157.     gmpcNone,                   /* E7 - Set tremolo type */
  158.     gmpcSetPanning16,           /* E8 - Set panning (extension) */
  159.     gmpcPTRetrig,               /* E9 - Retrig note */
  160.     gmpcFineVolSlideUp,         /* EA - Fine volume slide up */
  161.     gmpcFineVolSlideDown,       /* EB - Fine volume slide down */
  162.     gmpcNoteCut,                /* EC - Note cut */
  163.     gmpcNoteDelay,              /* ED - Note delay */
  164.     gmpcPatternDelay,           /* EE - Pattern delay */
  165.     gmpcNone                    /* EF - Invert loop */
  166. };
  167.  
  168.  
  169.  
  170.  
  171. /****************************************************************************\
  172. *       Module loader buffers and file handle. These variables are static
  173. *       instead of local so that a separate deallocation can be used which
  174. *       will be called before exiting in error situations
  175. \****************************************************************************/
  176. static fileHandle f;                    /* file handle for module file */
  177. static int      fileOpened;             /* 1 if module file has been opened */
  178. static gmpModule *module;               /* pointer to GMP module structure */
  179. static xmHeader *header;                /* pointer to FT2 module header */
  180. static uchar    *instUsed;              /* instrument used flags */
  181. static xmPattern *xmPatt;               /* pointer to XM pattern data */
  182. static gmpPattern *convPatt;            /* pointer to converted pattern data*/
  183. static uchar    *smpBuf;                /* sample loading buffer */
  184. static unsigned numChans;               /* number of channels in module */
  185. static xmInstHeader *xmInst;            /* XM instrument header */
  186. static xmInstSampleHeader *xmInstSmp;   /* XM instrument sample header */
  187. static xmSampleHeader *xmSample;        /* XM sample header */
  188. static int      maxInstUsed;            /* maximum used instrument number */
  189.  
  190.  
  191.  
  192.  
  193.  
  194. /****************************************************************************\
  195. *
  196. * Function:     int ConvertPattern(xmPattern *srcPatt, gmpPattern *destPatt,
  197. *                   unsigned *convLen);
  198. *
  199. * Description:  Converts a pattern from FT2 to GMP internal format.
  200. *               Also updates instUsed flags.
  201. *
  202. * Input:        xmPattern *srcPatt      pointer to pattern in FT2 format
  203. *               gmpPattern *destPatt    pointer to destination GMP pattern
  204. *               unsigned *convLen       pointer to converted pattern length
  205. *
  206. * Returns:      MIDAS error code. Converted pattern length (in bytes,
  207. *               including header) is written to *convLen.
  208. *
  209. \****************************************************************************/
  210.  
  211. static int ConvertPattern(xmPattern *srcPatt, gmpPattern *destPatt,
  212.     unsigned *convLen)
  213. {
  214.     uchar       *src = &srcPatt->data[0];
  215.     uchar       *dest = &destPatt->data[0];
  216.     unsigned    row, chan;
  217.     unsigned    len;
  218.     uchar       note, inst, command, infobyte, vol, compInfo;
  219.     uchar       xmComp;
  220.     uchar       gmpCommand;
  221.  
  222. /*
  223.    ***********************
  224.    *   Pattern format:     *
  225.    ***********************
  226.  
  227.    The patterns are stored as ordinary MOD patterns, except that each
  228.    note is stored as 5 bytes:
  229.  
  230.       ?      1     (byte) Note (0-71, 0 = C-0)
  231.      +1      1     (byte) Instrument (0-128)
  232.      +2      1     (byte) Volume column byte (see below)
  233.      +3      1     (byte) Effect type
  234.      +4      1     (byte) Effect parameter
  235.  
  236.    A simle packing scheme is also adopted, so that the patterns not become
  237.    TOO large: Since the MSB in the note value is never used, if is used for
  238.    the compression. If the bit is set, then the other bits are interpreted
  239.    as follows:
  240.  
  241.       bit 0 set: Note follows
  242.       1 set: Instrument follows
  243.       2 set: Volume column byte follows
  244.       3 set: Effect follows
  245.       4 set: Guess what!
  246. */
  247.  
  248.     if ( srcPatt->numRows > 256 || srcPatt->numRows == 0 )
  249.         return errInvalidModule;
  250.  
  251.     /* Check if the pattern is empty: */
  252.     if ( srcPatt->pattDataSize == 0 )
  253.     {
  254.         /* Write row end marker for each row: */
  255.         for ( row = 0; row < srcPatt->numRows; row++ )
  256.             *(dest++) = 0;
  257.  
  258.         /* Write number of rows to pattern header: */
  259.         destPatt->rows = srcPatt->numRows;
  260.  
  261.         /* Write converted pattern length to header and return it in
  262.            *convLen: */
  263.         *convLen = destPatt->length = srcPatt->numRows + sizeof(gmpPattern);
  264.         return OK;
  265.     }
  266.  
  267.     for ( row = 0; row < srcPatt->numRows; row++ )
  268.     {
  269.         for ( chan = 0; chan < numChans; chan++ )
  270.         {
  271.             /* No data for this channel yet: */
  272.             compInfo = 0;
  273.             note = 0xFF;
  274.             inst = 0xFF;
  275.             command = 0;
  276.             infobyte = 0;
  277.             vol = 0;
  278.             gmpCommand = 0;
  279.  
  280.             /* Get note number/compression info from pattern data: */
  281.             xmComp = *src;
  282.  
  283.             /* If the most significant bit in the read byte is 1 the byte
  284.                contains compression info bits, otherwise it is the note
  285.                number and all fields are present: */
  286.             if ( xmComp & 0x80 )
  287.             {
  288.                 /* The byte is compression info - continue from next byte: */
  289.                 src++;
  290.                 xmComp &= 0x7F;
  291.             }
  292.             else
  293.             {
  294.                 /* The byte is note number - mark that all fields are present
  295.                    and use current byte as the note number: */
  296.                 xmComp = 0x7F;
  297.             }
  298.  
  299.             /* Check if there is a new note: */
  300.             if ( xmComp & 1 )
  301.             {
  302.                 /* Check that the note is not key off and convert it to GMP
  303.                    internal format: */
  304.                 if ( *src > 96 )
  305.                     note = 0xFE;
  306.                 else
  307.                     note = ((((*src)-1) / 12) << 4) | (((*src)-1) % 12);
  308.  
  309.                 src++;
  310.  
  311.                 /* Mark that there is a new note: */
  312.                 compInfo |= 32;
  313.             }
  314.  
  315.             /* Check if there is a new instrument: */
  316.             if ( xmComp & 2 )
  317.             {
  318.                 /* Get the instrument number: */
  319.                 inst = (*(src++)) - 1;
  320.  
  321.                 /* [Petteri] 06 Dec 1997 - Why was this here?
  322.                 if ( note == 0xFE )
  323.                     inst = 0xFF;
  324.                 */
  325.  
  326.                 if ( inst != 0xFF )
  327.                 {
  328.                     /* Check if the instrument number if above maximum instrument
  329.                        number used: */
  330.                     if ( inst > maxInstUsed )
  331.                         maxInstUsed = inst;
  332.  
  333.                     /* Mark instrument used: */
  334.                     instUsed[inst] = 1;
  335.  
  336.                     /* Mark that there is a new instrument: */
  337.                     compInfo |= 32;
  338.                 }
  339.             }
  340.  
  341.             /* Check if there is a volume column byte: */
  342.             if ( xmComp & 4 )
  343.             {
  344.                 /* Get the volume column byte: */
  345.                 vol = *(src++);
  346.  
  347.                 /* Ignore the volume column byte if it is zero: */
  348.                 if ( vol != 0 )
  349.                 {
  350.                     /* Convert the byte to volume number if it is a set
  351.                        volume command: */
  352.                     if ( (vol >= 0x10) && (vol <= 0x50) )
  353.                         vol -= 0x10;
  354.  
  355.                     /* Mark that there is a volume column byte: */
  356.                     compInfo |= 64;
  357.                 }
  358.             }
  359.  
  360.             /* Check if there is a command: */
  361.             if ( xmComp & 8 )
  362.             {
  363.                 /* Get the command number: */
  364.                 command = *(src++);
  365.             }
  366.  
  367.             /* Check if there is an infobyte: */
  368.             if ( xmComp & 16 )
  369.             {
  370.                 /* Get the infobyte: */
  371.                 infobyte = *(src++);
  372.             }
  373.  
  374.             /* If there is a command or an infobyte we need to write the
  375.                command to the destination pattern: */
  376.             if ( (command != 0) || (infobyte != 0) )
  377.             {
  378.                 /* Convert command to GMP command number: */
  379.                 gmpCommand = ft2Commands[command];
  380.  
  381.                 /* Special commands */
  382.                 switch ( command )
  383.                 {
  384.                     case 0x0E:
  385.                         /* Command E - check actual command number: */
  386.                         gmpCommand = ft2ECommands[infobyte >> 4];
  387.                         infobyte = infobyte & 0x0F;
  388.                         break;
  389.  
  390.                     case 0x0F:
  391.                         /* Fasttracker 2 command 0Fh - set speed or set tempo.
  392.                            If infobyte >= 32, the BPM tempo is changed: */
  393.                         if ( infobyte >= 32 )
  394.                             gmpCommand = gmpcSetTempo;
  395.                         else
  396.                             gmpCommand = gmpcSetSpeed;
  397.                         break;
  398.  
  399.                     case ('K' - 'F' + 0x0F):
  400.                         /* FT2 command K - release note. Convert to release
  401.                            note note number: */
  402.                         note = 254;
  403.                         compInfo |= 32;
  404.                         gmpCommand = gmpcNone;
  405.                         break;
  406.  
  407.                     case ('X' - 'F' + 0x0F):
  408.                         /* FT2 command X - eXtra fine slides.  Convert
  409.                             to separate commands: */
  410.                         gmpCommand = gmpcNone;
  411.                         if ( (infobyte & 0xF0) == 0x10 )
  412.                             gmpCommand = gmpcExtraFineSlideUp;
  413.                         if ( (infobyte & 0xF0) == 0x20 )
  414.                             gmpCommand = gmpcExtraFineSlideDown;
  415.  
  416.                         infobyte = infobyte & 0x0F;
  417.                         break;
  418.                 }
  419.  
  420.                 /* Mark that there is a command: */
  421.                 if ( gmpCommand != gmpcNone )
  422.                     compInfo |= 128;
  423.             }
  424.  
  425.             /* If the compression information is nonzero, there is some
  426.                data for this channel: */
  427.             if ( compInfo != 0 )
  428.             {
  429.                 /* Set channel number to lower 5 bits of the compression info
  430.                    and write it to destination: */
  431.                 compInfo |= chan;
  432.                 *(dest++) = compInfo;
  433.  
  434.                 /* Check if there a note+instrument pair: */
  435.                 if ( compInfo & 32 )
  436.                 {
  437.                     /* Write note and instrument numbers: */
  438.                     *(dest++) = note;
  439.                     *(dest++) = inst;
  440.                 }
  441.  
  442.                 /* Check if there is a volume column byte: */
  443.                 if ( compInfo & 64 )
  444.                 {
  445.                     /* Write the volume column byte: */
  446.                     *(dest++) = vol;
  447.                 }
  448.  
  449.                 /* Check if there is a command: */
  450.                 if ( compInfo & 128 )
  451.                 {
  452.                     /* Write command and command infobyte: */
  453.                     *(dest++) = gmpCommand;
  454.                     *(dest++) = infobyte;
  455.                 }
  456.             }
  457.         }
  458.  
  459.         /* Write row end marker: */
  460.         *(dest++) = 0;
  461.     }
  462.  
  463.     /* Write number of rows to pattern header: */
  464.     destPatt->rows = srcPatt->numRows;
  465.  
  466.     /* Calculate converted pattern length: */
  467.     len = (unsigned) (dest  - ((uchar*) destPatt));
  468.  
  469.     /* Write converted pattern length to header and return it in *convLen: */
  470.     destPatt->length = len;
  471.     *convLen = len;
  472.  
  473.     return OK;
  474. }
  475.  
  476.  
  477.  
  478.  
  479. /****************************************************************************\
  480. *
  481. * Function:     void LoadError(void)
  482. *
  483. * Description:  Stops loading the module, deallocates all buffers and closes
  484. *               the file.
  485. *
  486. \****************************************************************************/
  487.  
  488. #define condFree(x) { if ( x != NULL ) if ( memFree(x) != OK) return; }
  489.  
  490. static void LoadError(void)
  491. {
  492.     /* Close file if opened. Do not process errors. */
  493.     if ( fileOpened )
  494.         if ( fileClose(f) != OK )
  495.             return;
  496.  
  497.     /* Attempt to deallocate module if allocated. Do not process errors. */
  498.     if ( module != NULL )
  499.         if ( gmpFreeModule(module) != OK )
  500.             return;
  501.  
  502.     /* Deallocate structures if allocated: */
  503.     condFree(header)
  504.     condFree(instUsed)
  505.     condFree(smpBuf)
  506.     condFree(xmInst)
  507.     condFree(xmInstSmp)
  508.     condFree(xmSample)
  509. }
  510.  
  511.  
  512.  
  513.  
  514. /****************************************************************************\
  515. *
  516. * Function:     int gmpLoadXM(char *fileName, int addSD, mpModule **module)
  517. *
  518. * Description:  Loads a Fasttracker 2 module to memory in Generic Module
  519. *               Player module format
  520. *
  521. * Input:        char *fileName          module file name
  522. *               int addSD               1 if module samples should be added to
  523. *                                       the current Sound Device, 0 if not
  524. *               int (*SampleCallback)(...)  pointer to callback function that
  525. *                                       will be called after sample has been
  526. *                                       added to Sound Device, but before
  527. *                                       sample data is deallocated
  528. *               mpModule **module       pointer to GMP module pointer
  529. *
  530. * Returns:      MIDAS error code
  531. *
  532. \****************************************************************************/
  533.  
  534. int CALLING gmpLoadXM(char *fileName, int addSD, int
  535.     (CALLING *SampleCallback)(sdSample *sdsmp, gmpSample *gmpsmp),
  536.     gmpModule **_module)
  537. {
  538.     int             error;              /* MIDAS error code */
  539.     static gmpInstrument *inst;
  540.     unsigned        i, s;
  541.     unsigned        n;
  542.     unsigned        numSamplesUsed;
  543.     ulong           maxSample;
  544.     static unsigned convPattLen;
  545.     static long     filePos;
  546.     static gmpSample *sample;
  547.     static sdSample sdSmp;
  548.     ulong           smpTotal;
  549.     long            smpStart;
  550.     long            skip;
  551.     gmpEnvelope     *env;
  552.     uchar           *smpData;
  553.     int             d;
  554.     unsigned        numInsts;
  555.     unsigned        maxPatt;
  556. #ifndef NOEMS
  557.     uchar           *patt;
  558. #endif
  559.  
  560.  
  561.     /* point buffers to NULL and set fileOpened to 0 so that LoadError()
  562.        can be called at any point: */
  563.     fileOpened = 0;
  564.     module = NULL;
  565.     header = NULL;
  566.     instUsed = NULL;
  567.     xmPatt = NULL;
  568.     convPatt = NULL;
  569.     smpBuf = NULL;
  570.     xmInst = NULL;
  571.     xmInstSmp = NULL;
  572.     xmSample = NULL;
  573.  
  574. #ifdef DEBUGMESSAGES
  575.     puts("Loading header");
  576. #endif
  577.  
  578.     /* Allocate memory for XM module header: */
  579.     if ( (error = memAlloc(sizeof(xmHeader), (void**) &header)) != OK )
  580.         PASSERR()
  581.  
  582.     /* Open module file: */
  583.     if ( (error = fileOpen(fileName, fileOpenRead, &f)) != OK )
  584.         PASSERR()
  585.     fileOpened = 1;
  586.  
  587.     /* Allocate memory for the module structure: */
  588.     if ( (error = memAlloc(sizeof(gmpModule), (void**) &module)) != OK )
  589.         PASSERR()
  590.  
  591.     /* Clear module structure so that it can safely be deallocated with
  592.        gmpFreeModule() at any point: */
  593.     module->panning = NULL;
  594.     module->songData = NULL;
  595.     module->instruments = NULL;
  596.     module->patterns = NULL;
  597.  
  598.     /* Read Fasttracker module header: */
  599.     if ( (error = fileRead(f, header, sizeof(xmHeader))) != OK )
  600.         PASSERR()
  601.  
  602.     /* Skip possible unused bytes at the end of the module header: */
  603.     if ( (error = fileSeek(f, header->hdrSize - sizeof(xmHeader) + 60,
  604.         fileSeekRelative)) != OK )
  605.         PASSERR()
  606.  
  607.     /* Check that the header contains a valid signature and the file format
  608.        version number is correct: */
  609.     if ( (!mMemEqual(header->signature, "Extended Module: ", 17)) ||
  610.         (header->version < 0x104) )
  611.     {
  612.         ERROR(errInvalidModule, ID_gmpLoadXM);
  613.         LoadError();
  614.         return errInvalidModule;
  615.     }
  616.  
  617.     /* Get number of channels from the header: */
  618.     numChans = header->numChans;
  619.     module->numChannels = numChans;
  620.  
  621.     /* Copy song name: */
  622.     mMemCopy(module->name, header->name, 20);
  623.     module->name[20] = 0;                   /* force terminating '\0' */
  624.  
  625.     module->songLength = header->songLength;    /* copy song length */
  626.     module->playMode = gmpFT2;              /* set FT2 playing mode */
  627.     module->masterVolume = 64;              /* maximum master volume */
  628.     module->speed = (uchar) header->speed;  /* copy initial speed */
  629.     module->tempo = (uchar) header->tempo;  /* copy initial tempo */
  630.     module->restart = header->restart;      /* copy restart position */
  631.     module->numPatts = header->numPatts;    /* copy number of patterns */
  632.  
  633.     /* Check if linear frequencies are used: */
  634.     if ( header->flags & xmLinearFreq )
  635.         module->playFlags.linFreqTable = 1;
  636.     else
  637.         module->playFlags.linFreqTable = 0;
  638.  
  639.     /* Allocate memory for channel initial panning positions: */
  640.     if ( (error = memAlloc(32 * sizeof(int), (void**) &module->panning))
  641.         != OK )
  642.         PASSERR()
  643.  
  644.     /* Set initial panning position to all middle: */
  645.     for ( i = 0; i < numChans; i++ )
  646.         module->panning[i] = 0x80;
  647.  
  648.     /* Allocate memory for song data: */
  649.     if ( (error = memAlloc(sizeof(ushort) * module->songLength,
  650.         (void**) &module->songData)) != OK )
  651.         PASSERR()
  652.  
  653.     /* Copy song data and find the maximum pattern used: */
  654.     maxPatt = 0;
  655.     for ( i = 0; i < module->songLength; i++ )
  656.     {
  657.         module->songData[i] = header->orders[i];
  658.         if ( module->songData[i] > maxPatt )
  659.             maxPatt = module->songData[i];
  660.     }
  661.  
  662.     /* If more patterns are used than there are in the file, allocate memory
  663.        for all of them: */
  664.     if ( maxPatt >= module->numPatts )
  665.         module->numPatts = maxPatt + 1;
  666.  
  667.     /* Allocate memory for pattern pointers: */
  668.     if ( (error = memAlloc(sizeof(gmpPattern*) * module->numPatts,
  669.         (void**) &module->patterns)) != OK )
  670.         PASSERR()
  671.  
  672.     /* Set all pattern pointers to NULL to mark them unallocated: */
  673.     for ( i = 0; i < module->numPatts; i++ )
  674.         module->patterns[i] = NULL;
  675.  
  676.     /* Allocate memory for instrument used flags: */
  677.     if ( (error = memAlloc(256, (void**)&instUsed)) != OK )
  678.         PASSERR()
  679.  
  680.     /* Mark all instruments unused: */
  681.     for ( i = 0; i < 256; i++ )
  682.         instUsed[i] = 0;
  683.  
  684.     /* Clear maximum instrument number used: */
  685.     maxInstUsed = 0;
  686.  
  687.     /* Allocate memory for pattern loading buffer: */
  688.     if ( (error = memAlloc(sizeof(xmPattern) + numChans * 5 * 256,
  689.         (void**) &xmPatt)) != OK )
  690.         PASSERR()
  691.  
  692.     /* Allocate memory for pattern conversion buffer: (maximum GMP pattern
  693.        data size is 6 bytes per row per channel plus header) */
  694.     if ( (error = memAlloc(numChans * 256 * 6 + sizeof(gmpPattern),
  695.         (void**) &convPatt)) != OK )
  696.         PASSERR()
  697.  
  698. #ifdef DEBUGMESSAGES
  699.     puts("Starting to load patterns");
  700. #endif
  701.  
  702.     /* Load and convert all patterns: */
  703.     for ( i = 0; i < module->numPatts; i++ )
  704.     {
  705. #ifdef DEBUGMESSAGES
  706.         printf("Pattern %i - ", i);
  707. #endif
  708.  
  709.         CHECKHEAP
  710.  
  711.         /* Check if this pattern is in file: */
  712.         if ( i < header->numPatts )
  713.         {
  714.             /* Read pattern header: */
  715.             if ( (error = fileRead(f, xmPatt, sizeof(xmPattern))) != OK )
  716.                 PASSERR()
  717.  
  718.             /* Skip possible unused bytes at the end of the pattern header: */
  719.             if ( (error = fileSeek(f, xmPatt->headerLength - sizeof(xmPattern),
  720.                 fileSeekRelative)) != OK )
  721.                 PASSERR()
  722.  
  723. #ifdef DEBUGMESSAGES
  724.         printf("sizeof(xmPattern) = %i - ", sizeof(xmPattern));
  725.         printf("offsetti = %u - ",
  726.            (unsigned) &xmPatt->numRows - (unsigned) xmPatt);
  727.             printf("Rows: %u, size %u, bsize %u - ", xmPatt->numRows,
  728.                 xmPatt->pattDataSize, 5 * 256 * numChans);
  729. #endif
  730.  
  731.             /* Read pattern data: */
  732.             if ( xmPatt->pattDataSize != 0 )
  733.             {
  734.                 if ( (error = fileRead(f, xmPatt->data, xmPatt->pattDataSize))
  735.                     != OK )
  736.                     PASSERR()
  737.             }
  738.         }
  739.         else
  740.         {
  741.             /* Pattern used but not in file - mark empty: */
  742.             xmPatt->pattDataSize = 0;
  743.             xmPatt->numRows = 64;
  744.  
  745. #ifdef DEBUGMESSAGES
  746.             printf("Empty -");
  747. #endif
  748.         }
  749.  
  750.         CHECKHEAP
  751.  
  752. #ifdef DEBUGMESSAGES
  753.         printf("Loaded, about to convert - ");
  754. #endif
  755.  
  756.         /* Convert the pattern data, checking the instruments used: */
  757.         if ( (error = ConvertPattern(xmPatt, convPatt, &convPattLen))
  758.             != OK )
  759.             PASSERR()
  760.  
  761. #ifdef DEBUGMESSAGES
  762.         printf("Conv. size %u - ", convPattLen);
  763. #endif
  764.  
  765.         CHECKHEAP
  766.  
  767. #ifndef NOEMS
  768.         if ( mUseEMS == 1 )             /* is EMS memory used? */
  769.         {
  770.             /* Allocate EMS for converted pattern data for current pattern in
  771.                module: */
  772.             if ( (error = emsAlloc(convPattLen, (emsBlock**)
  773.                 &module->patterns[i])) != OK )
  774.                 PASSERR()
  775.  
  776.             /* Map the allocated EMS block to conventional memory: */
  777.             if ( (error = emsMap((emsBlock*) module->patterns[i],
  778.                 (void**) &patt)) != OK)
  779.                 PASSERR()
  780.  
  781.             /* Copy the converted pattern data to the EMS block: */
  782.             mMemCopy(patt, convPatt, convPattLen);
  783.         }
  784.         else
  785. #endif
  786.         {
  787.             /* Allocate memory for converted pattern data for current pattern
  788.                in module: */
  789.             if ( (error = memAlloc(convPattLen, (void**)&module->patterns[i]))
  790.                 != OK )
  791.                 PASSERR()
  792.  
  793.             /* Copy the converted pattern data to the EMS block: */
  794.             mMemCopy(module->patterns[i], convPatt, convPattLen);
  795.         }
  796. #ifdef DEBUGMESSAGES
  797.         puts("OK");
  798. #endif
  799.         CHECKHEAP
  800.     }
  801.  
  802. #ifdef DEBUGMESSAGES
  803.     puts("Patterns loaded");
  804. #endif
  805.  
  806.     CHECKHEAP
  807.  
  808.     /* Deallocate pattern conversion buffer: */
  809.     if ( (error = memFree(convPatt)) != OK )
  810.         PASSERR()
  811.     convPatt = NULL;
  812.  
  813.     /* Deallocate pattern loading buffer: */
  814.     if ( (error = memFree(xmPatt)) != OK )
  815.         PASSERR()
  816.     xmPatt = NULL;
  817.  
  818.     /* Check actual number of instruments needed: (ensure that all used
  819.        instruments are added to Sound Device) */
  820.     if ( maxInstUsed >= header->numInsts )
  821.         numInsts = maxInstUsed + 1;
  822.     else
  823.         numInsts = header->numInsts;
  824.     module->numInsts = numInsts;
  825.  
  826. #ifdef DEBUGMESSAGES
  827.     printf("maxInstUsed = %i\n", maxInstUsed);
  828. #endif
  829.  
  830.  
  831.     /* Now we read all instrument and sample headers from the files,
  832.        converting them to GMPlayer structures. Offsets to sample data in the
  833.        file are saved in GMPlayer sample structure sample pointers (always
  834.        at least 32-bit) so that they can be read faster. This is necessary
  835.        as we need to be able to find out the maximum sample length to be able
  836.        to allocate a loading buffer for the samples. */
  837.  
  838.  
  839.     /* Allocate memory for instrument pointers: */
  840.     if ( (error = memAlloc(sizeof(gmpInstrument*) * numInsts,
  841.         (void**) &module->instruments)) != OK )
  842.         PASSERR()
  843.  
  844.     /* Set all instrument pointers to NULL to mark them unallocated: */
  845.     for ( i = 0; i < numInsts; i++ )
  846.         module->instruments[i] = NULL;
  847.  
  848.     /* Allocate memory for instrument and sample headers: */
  849.     if ( (error = memAlloc(sizeof(xmInstHeader), (void**) &xmInst)) != OK )
  850.         PASSERR()
  851.     if ( (error = memAlloc(sizeof(xmInstSampleHeader), (void**) &xmInstSmp))
  852.         != OK )
  853.         PASSERR()
  854.     if ( (error = memAlloc(sizeof(xmSampleHeader), (void**) &xmSample))
  855.         != OK )
  856.         PASSERR()
  857.  
  858.     maxSample = 0;
  859.  
  860.     for ( i = 0; i < numInsts; i++ )
  861.     {
  862. #ifdef DEBUGMESSAGES
  863.         printf("Loading instrument %i\n", i);
  864. #endif
  865.  
  866.         /* Check if the instrument number is below XM header maximum. If so,
  867.            load the instrument header, otherwise fill in necessary information
  868.            so that it appears like an empty header (which it is). Ugly? You
  869.            bet! */
  870.         if ( i < header->numInsts )
  871.         {
  872.             /* Read instrument header: */
  873.             if ( (error = fileRead(f, xmInst, sizeof(xmInstHeader))) != OK )
  874.                 PASSERR()
  875.  
  876.             skip = xmInst->instSize - sizeof(xmInstHeader);
  877.  
  878.             /* If the instrument has samples read instrument sample header: */
  879.             if ( xmInst->numSamples != 0 )
  880.             {
  881.                 if ( (error = fileRead(f, xmInstSmp, sizeof(xmInstSampleHeader)))
  882.                     != OK )
  883.                     PASSERR()
  884.  
  885.                 skip -= sizeof(xmInstSampleHeader);
  886.  
  887.                 /* Check number of samples used: */
  888.                 numSamplesUsed = 0;
  889.                 for ( n = 0; n < 96; n++ )
  890.                 {
  891.                     if ( xmInstSmp->noteSmpNums[n] >= numSamplesUsed )
  892.                         numSamplesUsed = xmInstSmp->noteSmpNums[n] + 1;
  893.                 }
  894.             }
  895.             else
  896.                 numSamplesUsed = 0;
  897.         }
  898.         else
  899.         {
  900.             /* Instrument not in the file is used - clear the structure: */
  901.             xmInst->instSize = 0;
  902.             xmInst->instName[0] = 0;
  903.             xmInst->instType = 0;
  904.             xmInst->numSamples = 0;
  905.             numSamplesUsed = 0;
  906.  
  907.             /* And how we love Triton! */
  908.             mMemCopy(&xmInst->instName[1], "S2 loves Triton!", 17);
  909.  
  910.             /* No data after the header: (what header? ;) */
  911.             skip = 0;
  912.         }
  913.  
  914.  
  915.         /* If instrument is used, it must have at least one sample (regardless
  916.            of what the XM instrument header says) */
  917.         if ( instUsed[i] )
  918.         {
  919.             if ( numSamplesUsed > 0 )
  920.                 n = numSamplesUsed;
  921.             else
  922.                 n = 1;
  923.         }
  924.         else
  925.         {
  926.             n = 0;
  927.         }
  928.  
  929.         /* Allocate memory for instrument and sample structures: */
  930.         if ( (error = memAlloc(sizeof(gmpInstrument) + n*sizeof(gmpSample),
  931.             (void**) &inst))
  932.             != OK )
  933.             PASSERR()
  934.         module->instruments[i] = inst;
  935.  
  936.         /* Copy instrument name: */
  937.         mMemCopy(inst->name, xmInst->instName, 22);
  938.         inst->name[22] = 0;
  939.  
  940.         inst->numSamples = n;
  941.         inst->used = instUsed[i];
  942.  
  943.         /* Clear all allocated samples so that the module can be deallocated
  944.            safely: */
  945.         sample = &inst->samples[0];
  946.         for ( s = 0; s < n; s++ )
  947.         {
  948.             sample->sdHandle = 0;
  949.             sample->sample = NULL;
  950.             sample->sampleType = smpNone;
  951.             sample->volume = 0;
  952.             sample->panning = panMiddle;
  953.             sample->baseTune = 0;
  954.             sample->finetune = 0;
  955.         }
  956.  
  957.         inst->noteSamples = NULL;
  958.         inst->volEnvelope = NULL;
  959.         inst->panEnvelope = NULL;
  960.  
  961.         /* Process instrument sample header: */
  962.         if ( xmInst->numSamples > 0 )
  963.         {
  964.             /* Check if we need a note sample number table: */
  965.             if ( numSamplesUsed > 1 )
  966.             {
  967.                 /* Allocate memory for table: */
  968.                 if ( (error = memAlloc(96, (void**) &inst->noteSamples))
  969.                     != OK )
  970.                     PASSERR()
  971.  
  972.                 /* Copy note numbers: */
  973.                 mMemCopy(inst->noteSamples, xmInstSmp->noteSmpNums, 96);
  974.  
  975. #ifdef DEBUGMESSAGES
  976.                 printf("\nnoteSamples!\n");
  977. #endif
  978.             }
  979.  
  980.             /* Check if volume envelope is used: */
  981.             if ( xmInstSmp->volEnvFlags & xmEnvelopeOn )
  982.             {
  983.                 /* Allocate memory for volume envelope info: */
  984.                 if ( (error = memAlloc(sizeof(gmpEnvelope), (void**)
  985.                     &inst->volEnvelope)) != OK )
  986.                     PASSERR()
  987.                 env = inst->volEnvelope;
  988.  
  989.                 /* Copy number of points in envelope: */
  990.                 env->numPoints = xmInstSmp->numVolPoints;
  991.  
  992.                 /* Set sustain point: */
  993.                 if ( xmInstSmp->volEnvFlags & xmEnvelopeSustain )
  994.                     env->sustain = xmInstSmp->volSustain;
  995.                 else
  996.                     env->sustain = -1;
  997.  
  998.                 /* Set loop start and end points: (FT2 ignores envelope
  999.                    loops where the start and end positions are the same) */
  1000.                 if ( (xmInstSmp->volEnvFlags & xmEnvelopeLoop) &&
  1001.                     (xmInstSmp->volLoopStart != xmInstSmp->volLoopEnd) )
  1002.                 {
  1003.                     env->loopStart = xmInstSmp->volLoopStart;
  1004.                     env->loopEnd = xmInstSmp->volLoopEnd;
  1005.                 }
  1006.                 else
  1007.                 {
  1008.                     env->loopStart = env->loopEnd = -1;
  1009.                 }
  1010.  
  1011.                 /* Copy envelope points: */
  1012.                 mMemCopy(env->points, xmInstSmp->volEnvelope, 48);
  1013.             }
  1014.             else
  1015.                 inst->volEnvelope = NULL;
  1016.  
  1017.             /* Check if panning envelope is used: */
  1018.             if ( xmInstSmp->panEnvFlags & xmEnvelopeOn )
  1019.             {
  1020.                 /* Allocate memory for volume envelope info: */
  1021.                 if ( (error = memAlloc(sizeof(gmpEnvelope), (void**)
  1022.                     &inst->panEnvelope)) != OK )
  1023.                     PASSERR()
  1024.                 env = inst->panEnvelope;
  1025.  
  1026.                 /* Copy number of points in envelope: */
  1027.                 env->numPoints = xmInstSmp->numPanPoints;
  1028.  
  1029.                 /* Set sustain point: */
  1030.                 if ( xmInstSmp->panEnvFlags & xmEnvelopeSustain )
  1031.                     env->sustain = xmInstSmp->panSustain;
  1032.                 else
  1033.                     env->sustain = -1;
  1034.  
  1035.                 /* Set loop start and end points: (FT2 ignores envelope
  1036.                    loops where the start and end positions are the same) */
  1037.                 if ( (xmInstSmp->panEnvFlags & xmEnvelopeLoop) &&
  1038.                      (xmInstSmp->panLoopStart != xmInstSmp->panLoopEnd) )
  1039.                 {
  1040.                     env->loopStart = xmInstSmp->panLoopStart;
  1041.                     env->loopEnd = xmInstSmp->panLoopEnd;
  1042.                 }
  1043.                 else
  1044.                 {
  1045.                     env->loopStart = env->loopEnd = -1;
  1046.                 }
  1047.  
  1048.                 /* Copy envelope points: */
  1049.                 mMemCopy(env->points, xmInstSmp->panEnvelope, 48);
  1050.             }
  1051.             else
  1052.                 inst->panEnvelope = NULL;
  1053.  
  1054.             /* Copy volume fade-out speed: */
  1055.             inst->volFadeout = xmInstSmp->volFadeout;
  1056.  
  1057.             /* Copy instrument auto-vibrato information: */
  1058.             inst->vibType = xmInstSmp->vibType;
  1059.             inst->vibSweep = xmInstSmp->vibSweep;
  1060.             inst->vibDepth = xmInstSmp->vibDepth;
  1061.             inst->vibRate = xmInstSmp->vibRate;
  1062.         }
  1063.  
  1064.         /* Skip possible unnecessary bytes at the end of the instrument
  1065.            header: */
  1066.         if ( (error = fileSeek(f, skip, fileSeekRelative)) != OK )
  1067.             PASSERR()
  1068.  
  1069.         /* Get current file position: */
  1070.         if ( (error = fileGetPosition(f, &filePos)) != OK )
  1071.             PASSERR()
  1072.  
  1073.         /* Calculate start offset for first sample: */
  1074.         smpStart = filePos + xmInst->numSamples * xmInstSmp->headerSize;
  1075.  
  1076.         /* Total sample length for this instrument: */
  1077.         smpTotal = 0;
  1078.  
  1079.         /* Load and convert all sample headers and calculate total sample
  1080.            length: */
  1081.         sample = &inst->samples[0];
  1082.         for ( s = 0; s < xmInst->numSamples; s++ )
  1083.         {
  1084.             /* Read sample header: */
  1085.             if ( (error = fileRead(f, xmSample, sizeof(xmSampleHeader)))
  1086.                 != OK )
  1087.                 PASSERR()
  1088.  
  1089.             /* Convert sample header if it used: */
  1090.             if ( s < inst->numSamples )
  1091.             {
  1092.                 /* Point sample->fileOffset to sample data start: */
  1093.                 sample->fileOffset = smpStart;
  1094.  
  1095.                 /* Copy sample name: */
  1096.                 mMemCopy(sample->name, xmSample->smpName, 22);
  1097.                 sample->name[22] = 0;
  1098.  
  1099.                 /* Copy sample information: */
  1100.                 sample->sampleLength = xmSample->smpLength;
  1101.                 sample->loop1Start = xmSample->loopStart;
  1102.                 sample->loop1End = xmSample->loopStart + xmSample->loopLength;
  1103.                 sample->volume = xmSample->volume;
  1104.                 sample->panning = (int) ((unsigned) xmSample->panning);
  1105.                 sample->baseTune = xmSample->relNote;
  1106.                 sample->finetune = (int) ((signed char) xmSample->finetune);
  1107.                 sample->loop2Type = loopNone;
  1108.  
  1109.                 /* Convert sample type: */
  1110.                 if ( xmSample->flags & xmSample16bit )
  1111.                     sample->sampleType = smp16bit;
  1112.                 else
  1113.                     sample->sampleType = smp8bit;
  1114.  
  1115.                 /* Update maximum sample length: */
  1116.                 if ( sample->sampleLength > maxSample )
  1117.                     maxSample = sample->sampleLength;
  1118.  
  1119.                 /* Convert sample loop type information: */
  1120.                 switch ( xmSample->flags & 3 )
  1121.                 {
  1122.                     case 1:
  1123.                         /* Unidirectional loop: */
  1124.                         sample->loopMode = sdLoop1;
  1125.                         sample->loop1Type = loopUnidir;
  1126.                         break;
  1127.  
  1128.                     case 2:
  1129.                         /* Bidirectional loop: */
  1130.                         sample->loopMode = sdLoop1;
  1131.                         sample->loop1Type = loopBidir;
  1132.                         break;
  1133.  
  1134.                     default:
  1135.                         /* No loop: */
  1136.                         sample->loopMode = sdLoopNone;
  1137.                         sample->loop1Type = loopNone;
  1138.                         break;
  1139.                 }
  1140.  
  1141.                 /* Check that the loop is legal if there is one: */
  1142.                 if ( sample->loop1End == sample->loop1Start )
  1143.                 {
  1144.                     sample->loopMode = sdLoopNone;
  1145.                     sample->loop1Type = loopNone;
  1146.                 }
  1147.             }
  1148.  
  1149.             /* Add sample length to sample total: */
  1150.             smpTotal += xmSample->smpLength;
  1151.  
  1152.             /* Update sample data start offset: */
  1153.             smpStart += xmSample->smpLength;
  1154.  
  1155.             /* Skip possible unused data at the end of sample header: */
  1156.             if ( (error = fileSeek(f, xmInstSmp->headerSize -
  1157.                 sizeof(xmSampleHeader), fileSeekRelative)) != OK )
  1158.                 PASSERR();
  1159.  
  1160.             sample++;
  1161.         }
  1162.  
  1163.         /* Create an empty sample header if a sample was allocated but not
  1164.            loaded: */
  1165.         if ( (n != 0) && (xmInst->numSamples == 0) )
  1166.         {
  1167.             sample->name[0] = 0;
  1168.             sample->sample = NULL;
  1169.             sample->sampleType = smpNone;
  1170.             sample->volume = 0;
  1171.             sample->panning = panMiddle;
  1172.             sample->sdHandle = 0;
  1173.         }
  1174.  
  1175.         /* Seek to the start of next instrument header: */
  1176.         if ( (error = fileSeek(f, smpStart, fileSeekAbsolute)) != OK )
  1177.             PASSERR();
  1178.  
  1179.         CHECKHEAP
  1180.     }
  1181.  
  1182.  
  1183.     /* Deallocate memory instrument and sample headers: */
  1184.     if ( (error = memFree(xmInst)) != OK )
  1185.         PASSERR()
  1186.     xmInst = NULL;
  1187.     if ( (error = memFree(xmInstSmp)) != OK )
  1188.         PASSERR()
  1189.     xmInstSmp = NULL;
  1190.     if ( (error = memFree(xmSample)) != OK )
  1191.         PASSERR()
  1192.     xmSample = NULL;
  1193.  
  1194.  
  1195.     /* Check that the maximum sample length is below the Sound Device limit:*/
  1196.     if ( maxSample > SMPMAX )
  1197.     {
  1198.         ERROR(errInvalidInst, ID_gmpLoadXM);
  1199.         LoadError();
  1200.         return errInvalidInst;
  1201.     }
  1202.  
  1203.     /* If samples should be added to Sound Device, allocate memory for sample
  1204.        loading buffer: */
  1205.     if ( addSD )
  1206.     {
  1207.         if ( (error = memAlloc(maxSample, (void**) &smpBuf)) != OK )
  1208.             PASSERR()
  1209.     }
  1210.  
  1211.     /* Load all samples, convert the sample data and add the samples to Sound
  1212.        Device if necessary: */
  1213.     for ( i = 0; i < numInsts; i++ )
  1214.     {
  1215.         inst = module->instruments[i];
  1216.  
  1217.         /* Load all samples for this instrument: */
  1218.         sample = &inst->samples[0];
  1219.         for ( s = 0; s < inst->numSamples; s++ )
  1220.         {
  1221. #ifdef DEBUGMESSAGES
  1222.             printf("Loading sample %i for instrument %i - ", s, i);
  1223. #endif
  1224.             CHECKHEAP
  1225.  
  1226.             if ( sample->sampleType == smpNone )
  1227.             {
  1228. #ifdef DEBUGMESSAGES
  1229.                 puts("no sample");
  1230. #endif
  1231.                 /* There is no sample - just build an empty Sound Device
  1232.                    sample structure: */
  1233.                 sdSmp.sampleType = smpNone;
  1234.                 sdSmp.samplePos = sdSmpNone;
  1235.                 sdSmp.sample = NULL;
  1236.             }
  1237.             else
  1238.             {
  1239. #ifdef DEBUGMESSAGES
  1240.                 printf("sample, len = %u\n", sample->sampleLength);
  1241. #endif
  1242.                 /* There is a sample. If sample data should not be added to
  1243.                    Sound Device, allocate memory for the sample data and
  1244.                    point smpBuf there: */
  1245.                 if ( (!addSD) && (sample->sampleLength > 0) )
  1246.                 {
  1247.                     smpBuf = NULL;
  1248.                     if ( (error = memAlloc(sample->sampleLength, (void**)&smpBuf))
  1249.                         != OK )
  1250.                         PASSERR()
  1251.                     sample->sample = smpBuf;
  1252.                 }
  1253.                 else
  1254.                 {
  1255.                     /* Sample is added to the Sound Device - sample data is
  1256.                        not available: */
  1257.                     sample->sample = NULL;
  1258.                 }
  1259.  
  1260.                 /* Seek to beginning of sample data in file: */
  1261.                 if ( (error = fileSeek(f, sample->fileOffset,
  1262.                     fileSeekAbsolute)) != OK )
  1263.                     PASSERR();
  1264.  
  1265.                 /* Read the sample data: */
  1266.                 if ( sample->sampleLength > 0 )
  1267.                 {
  1268.                     if ( sample->sampleLength > maxSample )
  1269.                     {
  1270. #ifdef DEBUGMESSAGES
  1271.                         puts("BIG trouble!");
  1272. #endif
  1273.                     }
  1274.                     else
  1275.                     {
  1276. #ifdef DEBUGMESSAGES
  1277.                         printf("Reading %i bytes to %p\n",
  1278.                             sample->sampleLength, smpBuf);
  1279. #endif
  1280.                         if ( (error = fileRead(f, smpBuf,
  1281.                             sample->sampleLength)) != OK)
  1282.                             PASSERR();
  1283. #ifdef DEBUGMESSAGES
  1284.                         printf("Done\n");
  1285. #endif
  1286.                         CHECKHEAP
  1287.                     }
  1288.                 }
  1289.                 else
  1290.                 {
  1291.                     sample->sampleType = smpNone;
  1292.                 }
  1293.  
  1294. #ifdef DEBUGMESSAGES
  1295.                 printf("smpBuf = %p, len = %ld\n", smpBuf, maxSample);
  1296. #endif
  1297.  
  1298. #if 0   /* 16-bit sample support removed for now */
  1299.                 /* The sample data is in delta format. */
  1300.                 if ( sample->sampleType == smp16bit )
  1301.                 {
  1302.                     /* 16-bit sample */
  1303. #ifdef DEBUGMESSAGES
  1304.                     puts("16-bit sample data!");
  1305. #endif
  1306.                     sdSmp.sampleType = smp16bit;
  1307.                     smpData = smpBuf;
  1308.                     d = 0;
  1309.                     for ( n = 0; n < (sample->sampleLength / 2); n++ )
  1310.                     {
  1311.                         d += (int) *((signed short*) smpData);
  1312.                         *((signed short*) smpData) = d;
  1313.                         smpData += 2;
  1314.                     }
  1315.                     CHECKHEAP
  1316.                 }
  1317.                 else
  1318.                 {
  1319.                     /* 8-bit sample */
  1320.                     sdSmp.sampleType = smp8bit;
  1321.                     smpData = smpBuf;
  1322.                     d = 0;
  1323.                     for ( n = 0; n < sample->sampleLength; n++ )
  1324.                     {
  1325.                         d += (int) *((signed char*) smpData);
  1326.                         *smpData = (uchar) (128 + d);
  1327.                         smpData++;
  1328.                     }
  1329.                 }
  1330.  
  1331.  
  1332.                 /* Set Sound Device sample type: */
  1333. #endif /* #if 0 */
  1334.  
  1335. /* Code from older version added */
  1336.  
  1337.                 /* The sample data is in delta format. Convert it to raw
  1338.                    unsigned 8-bit data: (FIXME - 16-bit samples!) */
  1339.                 if ( sample->sampleType == smp16bit )
  1340.                 {
  1341. #ifdef DEBUGMESSAGES
  1342.                     puts("Converting 16-bit sample data");
  1343. #endif
  1344.                     /* 16-bit sample - convert to 8-bit on the fly */
  1345.                     smpData = smpBuf;
  1346.                     d = 0;
  1347.                     for ( n = 0; n < (sample->sampleLength / 2); n++ )
  1348.                     {
  1349.                         d += (int) *((signed short*) smpData);
  1350.                         smpBuf[n] = (uchar) (128 + (d >> 8));
  1351.                         smpData += 2;
  1352.                     }
  1353. #ifdef DEBUGMESSAGES
  1354.                     puts("Converting sample structure");
  1355. #endif
  1356.                     /* Converted to 8-bit - update sample structure: */
  1357.                     sample->sampleLength /= 2;
  1358.                     sample->loop1Start /= 2;
  1359.                     sample->loop1End /= 2;
  1360.                     sample->sampleType = smp8bit;
  1361.                     /* (second loop not used) */
  1362.                     CHECKHEAP
  1363.                 }
  1364.                 else
  1365.                 {
  1366.                     /* 8-bit sample */
  1367.                     smpData = smpBuf;
  1368.                     d = 0;
  1369.                     for ( n = 0; n < sample->sampleLength; n++ )
  1370.                     {
  1371.                         d += (int) *((signed char*) smpData);
  1372.                         *smpData = (uchar) (128 + d);
  1373.                         smpData++;
  1374.                     }
  1375.                 }
  1376.  
  1377.                 /* Set Sound Device sample type: */
  1378.                 sdSmp.sampleType = smp8bit;
  1379.  
  1380.     /* end of added code */
  1381.  
  1382.                 /* Set Sound Device sample position in memory: */
  1383.                 sdSmp.samplePos = sdSmpConv;
  1384.  
  1385.                 /* Point Sound Device sample data to sample loading buffer: */
  1386.                 sdSmp.sample = smpBuf;
  1387.  
  1388.                 /* Point smpBuf to NULL if the sample is not added to Sound
  1389.                    Device to mark it should not be deallocated: */
  1390.                 if ( !addSD )
  1391.                     smpBuf = NULL;
  1392.             }
  1393.  
  1394.             sdSmp.sampleLength = sample->sampleLength;
  1395.             sdSmp.loopMode = sample->loopMode;
  1396.             sdSmp.loop1Start = sample->loop1Start;
  1397.             sdSmp.loop1End = sample->loop1End;
  1398.             sdSmp.loop1Type = sample->loop1Type;
  1399.  
  1400.             /* Set up the rest of Sound Device sample structure so that the sample
  1401.                can be added to the Sound Device: */
  1402.             if ( addSD )
  1403.             {
  1404.                 CHECKHEAP
  1405.  
  1406. #ifdef DEBUGMESSAGES
  1407.                 puts("gmpSD->AddSample()");
  1408. #endif
  1409.  
  1410.                 /* Add the sample to Sound Device and store the Sound Device
  1411.                    sample handle in sample->sdHandle: */
  1412.                 if ( (error = gmpSD->AddSample(&sdSmp, 1, &sample->sdHandle))
  1413.                     != OK)
  1414.                     PASSERR()
  1415.  
  1416.                 CHECKHEAP
  1417.  
  1418.                /* Call sample callback if used: */
  1419.                 if ( SampleCallback != NULL )
  1420.                 {
  1421.                     if ( (error = SampleCallback(&sdSmp, sample)) != OK )
  1422.                         PASSERR()
  1423.                 }
  1424.             }
  1425.             else
  1426.             {
  1427.                 /* Sample data has not been added to Sound Device: */
  1428.                 sample->sdHandle = 0;
  1429.             }
  1430.             sample++;
  1431.         }
  1432.     }
  1433.  
  1434. #ifdef DEBUGMESSAGES
  1435.     puts("Samples loaded");
  1436. #endif
  1437.     CHECKHEAP
  1438.  
  1439.     /* Deallocate sample loading buffer if allocated: */
  1440.     if ( addSD )
  1441.     {
  1442.         if ( (error = memFree(smpBuf)) != OK )
  1443.             PASSERR()
  1444.     }
  1445.     smpBuf = NULL;
  1446.  
  1447.     /* Deallocate instrument use flags: */
  1448.     if ( (error = memFree(instUsed)) != OK )
  1449.         PASSERR()
  1450.     instUsed = 0;
  1451.  
  1452.     /* Now we are finished loading. Close module file: */
  1453.     if ( (error = fileClose(f)) != OK)
  1454.         PASSERR()
  1455.     fileOpened = 0;
  1456.  
  1457.     /* Deallocate Fasttracker 2 module header: */
  1458.     if ( (error = memFree(header)) != OK )
  1459.         PASSERR();
  1460.  
  1461.     /* Return module pointer in *module: */
  1462.     *_module = module;
  1463.  
  1464.     return OK;
  1465. }
  1466.  
  1467.  
  1468. /*
  1469.  * $Log: loadxm.c,v $
  1470.  * Revision 1.12  1997/01/25 15:23:16  pekangas
  1471.  * The file is now closed properly if loading terminates to an error
  1472.  *
  1473.  * Revision 1.11  1997/01/16 18:41:59  pekangas
  1474.  * Changed copyright messages to Housemarque
  1475.  *
  1476.  * Revision 1.10  1997/01/07 19:18:15  pekangas
  1477.  * Now ignores envelope loops if start position = end position (as FT2 does)
  1478.  *
  1479.  * Revision 1.9  1996/12/30 23:37:19  jpaana
  1480.  * Cleaned up LoadError
  1481.  *
  1482.  * Revision 1.8  1996/10/06 16:48:38  pekangas
  1483.  * Fixed a potential signed/unsigned mismatch in panning
  1484.  *
  1485.  * Revision 1.7  1996/09/01 15:42:18  pekangas
  1486.  * Changed to use new style slides (no more signed infobytes)
  1487.  *
  1488.  * Revision 1.6  1996/07/13 20:14:11  pekangas
  1489.  * Eliminated Visual C warnings
  1490.  *
  1491.  * Revision 1.5  1996/07/13 18:24:02  pekangas
  1492.  * Fixed to compile with Visual C
  1493.  *
  1494.  * Revision 1.4  1996/06/14 16:23:40  pekangas
  1495.  * Removed heap checking to speed up loading
  1496.  *
  1497.  * Revision 1.3  1996/05/25 15:49:57  jpaana
  1498.  * Tried to fix for Linux, succeeded too
  1499.  *
  1500.  * Revision 1.2  1996/05/24 16:20:36  jpaana
  1501.  * Fixed to work with gcc
  1502.  *
  1503.  * Revision 1.1  1996/05/22 20:49:33  pekangas
  1504.  * Initial revision
  1505.  *
  1506. */
  1507.